﻿using Microsoft.AspNetCore.Http;
using System.Text.RegularExpressions;
using Urs.Core.Infrastructure;
using Urs.Services.Orders;

namespace tenpayApp
{
    /// <summary>
    /// 支付结果通知回调处理类
    /// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
    /// </summary>
    public class ResultNotify : Notify
    {
        public ResultNotify(IHttpContextAccessor httpContextAccessor)
            : base(httpContextAccessor)
        {
            this._httpContextAccessor = httpContextAccessor;
        }
        public override string ProcessNotify(string appId, string appKey, string partner)
        {
            var response = _httpContextAccessor.HttpContext.Response;
            WxPayData notifyData = GetNotifyData(appKey);
            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData(appKey);
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                return res.ToXml();
            }

            string transaction_id = notifyData.GetValue("transaction_id").ToString();
            string orderStr = notifyData.GetValue("out_trade_no").ToString();
            //查询订单，判断订单真实性
            if (!QueryOrder(transaction_id, appId, appKey, partner))
            {
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData(appKey);
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                return res.ToXml();
            }
            //查询订单成功
            else
            {
                int orderId = 0;
                Match m = Regex.Match(orderStr, "JsApi-Wap-(?<orderId>\\d+)-\\d+");
                if (m.Success)
                {
                    if (int.TryParse(m.Groups["orderId"].Value, out orderId))
                    {
                        var _orderService = EngineContext.Current.Resolve<IOrderService>();
                        var _orderProcessingService = EngineContext.Current.Resolve<IOrderProcessingService>();
                        var order = _orderService.GetOrderById(orderId);
                        if (order != null && _orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            _orderProcessingService.MarkOrderAsPaid(order);
                        }
                    }
                }
                WxPayData res = new WxPayData(appKey);
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                return res.ToXml();
            }
        }

        //查询订单
        public bool QueryOrder(string transaction_id, string appId, string appKey, string partner)
        {
            WxPayData req = new WxPayData(appKey);
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req, appId, appKey, partner);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}